package org.androidpn.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.androidpn.HospitalClientApplication;
import org.androidpn.model.CUserInfo;

import android.content.Context;

public class AppCache {
	private static AppCache sInstance;

	private Context mContext = HospitalClientApplication.getmInstance();

	/**
	 * @return AppCache singleton instance
	 */
	public static synchronized AppCache getInstance() {
		if (sInstance == null) {
			sInstance = new AppCache();
		}
		return sInstance;
	}

	/**
	 * user
	 * 
	 * @param 图片地址列表
	 * @return
	 * @throws AppException
	 */
	public void saveUserInfo(CUserInfo userInfo) {
		if (userInfo != null) {
			String key = "UserInfo";
			saveObject(userInfo, key);
		}
	}

	/**
	 * 用户信息
	 * 
	 * @return
	 * @throws ApiException
	 */
	public CUserInfo getUseInfo() {
		CUserInfo userInfo = null;
		String key = "UserInfo";
		userInfo = (CUserInfo) readObject(key);
		if (userInfo == null)
			userInfo = new CUserInfo();
		return userInfo;
	}

	/**
	 * 保存对象
	 * 
	 * @param ser
	 * @param file
	 * @throws IOException
	 */
	private boolean saveObject(Serializable ser, String file) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = mContext.openFileOutput(file, Context.MODE_PRIVATE);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(ser);
			oos.flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				oos.close();
			} catch (Exception e) {
			}
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 读取对象
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	private Serializable readObject(String file) {
		if (!isExistDataCache(file))
			return null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = mContext.openFileInput(file);
			ois = new ObjectInputStream(fis);
			return (Serializable) ois.readObject();
		} catch (FileNotFoundException e) {
		} catch (Exception e) {
			e.printStackTrace();
			// 反序列化失败 - 删除缓存文件
			if (e instanceof InvalidClassException) {
				File data = mContext.getFileStreamPath(file);
				data.delete();
			}
		} finally {
			try {
				ois.close();
			} catch (Exception e) {
			}
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return null;
	}

	/**
	 * 判断缓存是否存在
	 * 
	 * @param cachefile
	 * @return
	 */
	private boolean isExistDataCache(String cachefile) {
		boolean exist = false;
		File data = mContext.getFileStreamPath(cachefile);
		if (data.exists())
			exist = true;
		return exist;
	}
}
